class RubySearch
  def self.search(query, category=nil, limit=nil, province=nil, county=nil)
    unless category
      if county
        return Ad.find_by_sql("SELECT ads.* FROM ads INNER JOIN users ON users.id=ads.user_id WHERE users.county_id='#{county.id}' AND (ads.description LIKE '%#{query}%' OR ads.title LIKE '%#{query}%') "+("LIMIT #{limit}" if limit))
      end

      if province
        return Ad.find_by_sql("SELECT ads.* FROM ads INNER JOIN users ON users.id=ads.user_id INNER JOIN counties ON counties.id=users.county_id WHERE counties.province_id='#{province.id}' AND (ads.description LIKE '%#{query}%' OR ads.title LIKE '%#{query}%') "+("LIMIT #{limit}" if limit))
      end
    else
      result = Array.new
      ads = Category.find(category).recursive_ads(province,county).values
      ads.each do |ad|
        if ad.title.include?(query) ||
            ad.description.include?(query)
          result.push(ad)
          if limit && result.size() > limit
            return result
          end
        end
      end
      return result
    end

    return Ad.find_by_sql("SELECT ads.* FROM ads WHERE ads.description LIKE '%#{query}%' OR ads.title LIKE '%#{query}%' LIMIT #{limit}")
  end
end